#coding=utf8
"""
Warning:
    itchat.components.login:59 time.sleep(15) # 减慢QR code 的刷新
"""
import time

import itchat
import os
from itchat.content import *
import requests

import config
print(config.web_path)
# 获取当前脚本所在目录
current_dir = os.path.dirname(os.path.abspath(__file__))
lib_dir = os.path.join(current_dir, 'lib')
if not os.path.exists(lib_dir):
    os.makedirs(lib_dir)

@itchat.msg_register([TEXT, MAP, CARD, NOTE, SHARING])
def text_reply(msg):
    # logger.info(f"A new message ${msg['Text']}$ from {msg['User']['NickName']}")
    requests.get(config.web_path + f"/log?type=friend_text&msg={msg['Text']}&nickname={msg['User']['NickName']}")
    itchat.send(config.msg_head + config.out_temp_data(), msg['FromUserName']) # '%s: %s' % (msg['Type'], msg['Text']), msg['FromUserName']
    # 如果需要保存文本消息，可以在这里将消息内容写入文件并存储在 lib 目录
    config.out_communication({time.time():msg['Text']}, msg['User']['NickName'])

@itchat.msg_register([PICTURE, RECORDING, ATTACHMENT, VIDEO])
def download_files(msg):
    msg['Text'](os.path.join(lib_dir, msg['FileName']))
    return '@%s@%s' % ({'Picture': 'img', 'Video': 'vid'}.get(msg['Type'], 'fil'), msg['FileName'])

@itchat.msg_register(FRIENDS)
def add_friend(msg):
    itchat.add_friend(**msg['Text'])
    # logger.warning(f"Add friend {msg['Text']} from {msg['User']['NickName']}")
    requests.get(config.web_path + f"/log?type=new_friend&msg={msg['Text']}&nickname={msg['User']['NickName']}")
    itchat.send_msg(config.msg_head + 'Nice to meet you!', msg['RecommendInfo']['UserName'])

@itchat.msg_register(TEXT, isGroupChat=True)
def groupchat_reply(msg):
    if msg['isAt']:
        requests.get(config.web_path + f"/log?type=group_text&msg={msg['Content']}&nickname={msg['ActualNickName']}")
        itchat.send(config.msg_head + '@%s\u2005I received: %s' % (msg['ActualNickName'], msg['Content']), msg['FromUserName'])


itchat.auto_login(True)
itchat.run()